package com.usian.comment.service.impl;

import com.usian.comment.feign.UserFeign;
import com.usian.comment.service.CommentService;
import com.usian.model.comment.dtos.CommentDto;
import com.usian.model.comment.dtos.CommentLikeDto;
import com.usian.model.comment.dtos.CommentSaveDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentLike;
import com.usian.model.comment.vo.ApCommentVo;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserFeign userFeign;

    @Value("${likesCount}")
    private Integer likesCount;
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //校验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getContent() != null && dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "评论内容不能超过140字");
        }
        //获取用户信息
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApUser apUser = userFeign.findUserById(user.getId().longValue());
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前登录信息有误");
        }
        //保存评论
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId());
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setFlag((short) 0);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //参数校验
        if (dto.getCommentId()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //获取评论数据
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment!=null && dto.getOperation()==0){
            //查询是否已经点赞
            Query query = new Query();
            query.addCriteria(Criteria.where("commentId").is(apComment.getId()));
            List<ApCommentLike> list = mongoTemplate.find(query, ApCommentLike.class);
            //更新点赞数
            if (list.size()<=likesCount-1){
                apComment.setLikes(apComment.getLikes()+1);
                mongoTemplate.save(apComment);
            }
            //保存 APP评论信息点赞
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setAuthorId(user.getId());
            apCommentLike.setCommentId(apComment.getId());
            apCommentLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentLike);
        }else if (apComment!=null && dto.getOperation()==1){
            //取消点赞
            apComment.setLikes(apComment.getLikes() <= 0 ? 0 : apComment.getLikes() - 1);
            mongoTemplate.save(apComment);
            Query query = new Query();
            query.addCriteria(Criteria.where("authorId").is(apComment.getAuthorId()).and("commentId").is(apComment.getId()));
            mongoTemplate.remove(query,ApCommentLike.class);
        }
        //数据返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes",apComment.getLikes());
        return ResponseResult.okResult(resultMap);
    }

    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        //检查参数
        if(dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取当前文章的所有评论 创建时间倒序排序
        int size=10;
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate())).limit(size);
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        //未登录返回所有数据
        if (user==null){
            return ResponseResult.okResult(apComments);
        }

        //登录返回点赞数据
        //查询所有评论id
        List<String> idList = apComments.stream().map(a -> a.getId()).collect(Collectors.toList());
        //查询点赞表
        Query query1 = Query.query(Criteria.where("commentId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query1, ApCommentLike.class);
        List<ApCommentVo> resultList = new ArrayList<>();
        if (apComments!=null && apCommentLikes!=null){
            apComments.stream().forEach(c->{
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(c,apCommentVo);
                for (ApCommentLike apCommentLike : apCommentLikes) {
                    if (c.getId().equals(apCommentLike.getCommentId())){
                        apCommentVo.setOperation((short) 0);
                        break;
                    }
                }
                resultList.add(apCommentVo);
            });
            //返回已点赞评论
            return ResponseResult.okResult(resultList);
        }else {
            //返回所有评论
            return ResponseResult.okResult(apComments);
        }
    }

}
